package com.eleven.mall.service.impl;

import com.eleven.mall.mapper.ManagerMapper;
import com.eleven.mall.mapper.PermissionApiMapper;
import com.eleven.mall.mapper.PermissionMapper;
import com.eleven.mall.mapper.RoleMapper;
import com.eleven.mall.pojo.Menu;
import com.eleven.mall.pojo.entity.*;
import com.eleven.mall.service.RightService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: Rui_simple
 * @Date: 2022/10/21 15:58
 * @Description: RightServiceImpl
 * @Version 1.0.0
 */
@Service
@AllArgsConstructor
public class RightServiceImpl implements RightService {
    ManagerMapper managerMapper;
    RoleMapper roleMapper;
    PermissionMapper permissionMapper;
    PermissionApiMapper permissionApiMapper;

    /**
     * 获取左侧菜单列表
     * 1、根据用户id获取用户角色id
     * 2、通过角色id获取用户菜单id的列表
     * 3、根据菜单id列表 得到用户一级菜单
     * @param userId
     * @return
     */
    @Override
    public List<Menu> getMenusByUserId(Integer userId) {
        //1、
        Manager manager = managerMapper.selectByPrimaryKey(userId);
        Short roleId = manager.getRoleId().shortValue();
        //2、
        RoleWithBLOBs role = roleMapper.selectByPrimaryKey(roleId);
        //得到用户的id列表，转化为字符串数组
        String[] strIds = role.getPsIds().split(",");
        //将 strIds 数组转换为Short集合
        ArrayList<Short> ids = new ArrayList<>();
        for(String str : strIds) {
            ids.add(Short.parseShort(str));
        }
        //3、
        List<Menu> menuList = getMenusByParentId(ids, 0);
        for(Menu menu1: menuList) {
            // 根据 父菜单的 id 去找子菜单
            List<Menu> menuList2 = getMenusByParentId(ids, menu1.getId().intValue());
            //  将子菜单的列表 赋值给 children
            menu1.setChildren(menuList2);
            MenuPath(menuList2);
        }
        System.out.println(menuList);
        return menuList;
    }
    private List<Menu> getMenusByParentId(ArrayList<Short> ids, Integer parentId) {
        //3、根据菜单 id 列表得到 用户一级菜单
        PermissionExample example = new PermissionExample();
        example.createCriteria().andPsPidEqualTo(parentId.shortValue()).andPsIdIn(ids);

        List<Permission> permList = permissionMapper.selectByExample(example);
        ArrayList<Menu> menus = new ArrayList<>();
        for(Permission perm: permList) {
            System.out.println(perm);
            Menu menu = new Menu(perm.getPsId(), perm.getPsName(), "", null);
            menus.add(menu);
        }
        return menus;
    }

    private void MenuPath(List<Menu> menuList2){
        for (Menu menu : menuList2) {
            final Short menuId = menu.getId();
            final PermissionApi api = permissionApiMapper.selectByPsId(menuId.intValue());
            menu.setPath(api.getPsApiPath());
        }
    }
}
